package com.neuedu.corejava.ch14;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import sun.net.www.content.audio.basic;

public class ChatServer {

	public static void main(String[] args) {

		// 设置服务器的监听端口，启动服务器监听
		int port = 8888;
		ServerSocket serverSocket = null;
		Socket socket = null;
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
			// 1.启动服务器监听
			serverSocket = new ServerSocket(port);
			System.out.println("服务器启动成功，请使用客户端进行连接");
			// 2.等待客户端进行连接
			socket = serverSocket.accept();
			System.out.println("客户端连接成功");
			// 3.客户端连接后，打开输入流（准备从客户端读取数据输入）
			inputStream = socket.getInputStream();
			outputStream = socket.getOutputStream();
			// 4.读取客户端发送过来的数据,并接受--有阻塞作用
			byte[] buffer = new byte[521];
			int len = inputStream.read(buffer);
			// 5.对数据进行处理
			String string = new String(buffer, 0, len);
			System.out.println(string);

			outputStream.write(("reply from server" + string).getBytes("UTF-8"));
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 6.关闭输入流
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (socket != null) {
				try {
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (serverSocket != null) {
				try {
					serverSocket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		}
	}

}
